const router = require('koa-router')();
const { compare } = require('bcryptjs');

const {
  registerUser,
  loginUser,
  findDuplicateUser,
  findUserById,
  changeUserPwd,
  deleteUser
} = require('../controller/user');
const { verifyCode } = require('../controller/email');
const { SuccessResponse, ErrorResponse } = require('../model/Response');
const loginCheck = require('../middleware/loginCheck');

const prefix = '/api/user';
const nonLoginCheckRoutes = [
  { method: 'POST' },
  { method: 'POST', path: '/login' },
  { method: 'POST', path: '/unique' }
];

router.prefix(prefix);

router.use(async function (ctx, next) {
  if (
    nonLoginCheckRoutes.find(route => {
      return ctx.method === route.method
        && ctx.path === prefix + (route.path || '');
    })
  ) {
    await next();
  } else {
    await loginCheck(ctx, next);
  }
});

// register
router.post('/', async function (ctx) {
  const { username, password, email } = ctx.request.body;
  const isEmailPassed = await verifyCode(email);
  if (!isEmailPassed) {
    ctx.body = new ErrorResponse('邮箱未通过校验');
    return;
  }
  const res = await registerUser(username, password, email);
  ctx.body = new SuccessResponse(res, '注册成功');
});

// login
router.post('/login', async function (ctx) {
  const { loginName, password } = ctx.request.body;
  const res = await loginUser(loginName);
  if (!res) {
    ctx.body = new ErrorResponse('用户不存在，请检查用户名或邮箱');
    return;
  }

  const isPwdValid = await compare(password, res.hashPwd);
  if (!isPwdValid) {
    ctx.body = new ErrorResponse('密码错误，请检查密码输入');
    return;
  }

  const userInfo = {
    id: res.id,
    username: res.username,
    email: res.email
  };

  ctx.session.userInfo = userInfo;
  ctx.body = new SuccessResponse(userInfo, '登录成功');
});

// logout
router.post('/logout', async function (ctx) {
  ctx.session = null;
  ctx.body = new SuccessResponse();
});

// unique email
router.post('/unique', async function (ctx) {
  const fields = ctx.request.body;
  const exist = await findDuplicateUser(fields);
  ctx.body = new SuccessResponse(exist);
});

// findUser
router.get('/', async function (ctx) {
  const id = ctx.session.userInfo.id;
  const user = await findUserById(id);
  ctx.body = new SuccessResponse(user);
});

// change pwd
router.patch('/chgpwd', async function (ctx) {
  const { password: newPwd } = ctx.request.body;
  const id = ctx.session.userInfo.id;
  const res = await changeUserPwd(id, newPwd);
  if (!res) {
    ctx.body = new ErrorResponse();
    return;
  }
  ctx.body = new SuccessResponse();
});

router.delete('/', async function (ctx) {
  const id = ctx.session.userInfo.id;
  const res = await deleteUser(id);
  if (!res) {
    ctx.body = new ErrorResponse();
    return;
  }
  ctx.session = null;
  ctx.body = new SuccessResponse();
});

module.exports = router;
